package it.polimi.swKnights.SWIMv2.ejb.registration;

import it.polimi.swKnights.SWIMv2.ejb.entityBeans.ToConfirmUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyExistingException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidDateException;
import it.polimi.swKnights.SWIMv2.ejb.personalData.UserFinderLocal;
import it.polimi.swKnights.SWIMv2.utility.DateUtility;
import it.polimi.swKnights.SWIMv2.utility.MailSender;
import it.polimi.swKnights.SWIMv2.utility.PasswordUtility;
import it.polimi.swKnights.SWIMv2.utility.RandomStringGenerator;

import java.util.Calendar;
import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class UserCreationHandlerBean
 */
@Stateless
public class UserCreationHandler implements UserCreationHandlerRemote
{

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager manager; // manager handling the persistence data

	@EJB
	private UserFinderLocal userFinder;

	public void createNotConfirmedUser(String userName, String password,
			String email, String name, char sex, String surname, String bday,
			String city, String street, String number, String confirmUrl)
			throws AlreadyExistingException, InvalidDateException
	{
		if (!this.userFinder.existingUserName(userName))
		{

			// hash della password con sale
			password = setHashOfSaltPassword(password, email);
			ToConfirmUser toConfirmUser = new ToConfirmUser(userName, password,
					email);
			Date date = DateUtility.getDate(bday);
			Date today = new Date();
			if(today.before(date))
			{
				//compleanno nel passato
				throw new InvalidDateException();
			}

			toConfirmUser.setBirthday(date);
			toConfirmUser.setName(name);
			toConfirmUser.setSex(sex);
			toConfirmUser.setSurname(surname);
			
			Date expirationDate = this.getExpirationDate(today, 30);

			toConfirmUser.setValidUntil(expirationDate);
			toConfirmUser.setActivationCode(getActivationCode());

			this.manager.persist(toConfirmUser);
			sendConfirmationMail(userName, email,
					toConfirmUser.getActivationCode(), confirmUrl);
		}
		else
		{
			throw new AlreadyExistingException("Already existing user!");
		}

	}

	private String getActivationCode()
	{
		RandomStringGenerator rsg = new RandomStringGenerator();
		String s = rsg.nextSessionId();
		if (s.length() > 50)
			return s.substring(0, 48);
		else
			return s;

	}

	private void sendConfirmationMail(String userName, String email,
			String confirmCode, String webSite)
	{
		MailSender ms = new MailSender();

		String urlToConfirm = webSite + "confirmRegistration" + "?username="
				+ userName + "&" + "code=" + confirmCode;

		ms.setMessage("<h3> Dear "
				+ userName
				+ " thank you for choosing swimv2!"
				+ "you can confirm your registration clicking on the link : </h3> <br /> <br /> "
				+ "<a href=" + "\"" + urlToConfirm + "\">" + urlToConfirm
				+ "</a>");

		ms.sendMail(email);

	}

	private Date getExpirationDate(Date date, int days)
	{
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days); // minus number would decrement the days
		return cal.getTime();
	}

	private String setHashOfSaltPassword(String password, String email)
	{
		PasswordUtility pu = new PasswordUtility();

		return pu.getEncriptedPassword(password, email);
	}

}
